package com.hankol.winecellar


import android.app.AlertDialog
import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.ItemTouchHelper
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.dip2px
import com.baselibrary.extension.toast
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.hankol.winecellar.adapter.UploadImageVideoAdapter
import com.hankol.winecellar.bean.WineryEvaluateListBean
import com.hankol.winecellar.databinding.ActivityPublishWinecellarCommentBinding
import com.hankol.winecellar.utils.EditInputUtils
import com.hankol.winecellar.utils.RecyUtils
import com.media.utils.WineryAboutUtils
import com.hankol.winecellar.view.MyCircleProgress
import com.baselibrary.view.SpacesVerticalDec
import com.hankol.winecellar.viewmodel.WineCellarViewModel
import com.media.publish.bean.MultiImageResp
import com.media.publish.utils.UploadMediaUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**发布酒窖评论 【仅上传图片】
 * @author: merbng
 * @description:
 */
@Route(path = ActivityRouter.WINE_CELLAR.PUBLISH_WINEECELLAR_COMMEENT)
class PublishWinecellarCommentActivity : BaseActivity(), UploadImageVideoAdapter.OnItemClickListener, View.OnClickListener {

    private lateinit var viewModel: WineCellarViewModel
    private lateinit var binding: ActivityPublishWinecellarCommentBinding
    var dataBean: WineryEvaluateListBean? = null
    private lateinit var mImageVideoAdapter: UploadImageVideoAdapter
    private lateinit var mTouchHelper: ItemTouchHelper

    var imgPathUrlList = mutableListOf<String>()

    override fun getLayoutId(): Int {
        return R.layout.activity_publish_winecellar_comment
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(WineCellarViewModel::class.java)
        initView()
        initData()
        initListener()
        initObserver()
    }

    private lateinit var countDownTimer: CountDownTimer
    var uploadLoadingDialog: AlertDialog? = null
    fun showLoading() {
        uploadLoadingDialog = com.hankol.winecellar.utils.PopUtils.uploadLoadingDialog(this, object : com.hankol.winecellar.utils.PopUtils.ICallback4Progress {
            override fun progressCallback(progress: MyCircleProgress, tvProgress: TextView) {
                countDownTimer = object : CountDownTimer(60000, 3000) {
                    override fun onTick(millisUntilFinished: Long) {
                        val pro = (60000 - millisUntilFinished) / 1000
                        progress.setMax(60)
                        progress.setCurrent(pro.toInt())
                    }

                    override fun onFinish() {}
                }.start()
            }
        })
        if (!uploadLoadingDialog!!.isShowing) {
            uploadLoadingDialog!!.show()
        }
    }

    fun hideLoading() {
        countDownTimer.cancel()
        if (uploadLoadingDialog.checkNotNull()) {
            uploadLoadingDialog!!.dismiss()
        }
    }

    private fun initObserver() {
        viewModel.addCommentLD.observe(this, Observer {
            hideLoading()
            if (it.checkNotNull() && it) {
                //通知删除临时图片
                EventBusUtils.sendNotify(MessageBus.msgid_img_upload_succ_need_delete_temp)
                SensorsDataManager.instance.operatorCreateComment(SpUtils.getInstance().currentWineryInfo.wineryName.checkValue())
                HKToastUtils.showToast("发布成功")
                EventBusUtils.sendNotify(MessageBus.msgId_publish_winery_comment_success)
                finish()
            }
        })
    }

    private fun initListener() {
        binding.tvEnter.setOnClickListener(this)
        binding.ivBack.setOnClickListener { finish() }
    }

    private fun initData() {
        if (intent.extras.checkNotNull()) {
            dataBean = intent.extras?.getParcelable<WineryEvaluateListBean>(Constants.KEY_COMMENT_BEAN)
            dataBean?.let {
                setImgListData(CommonUtil.str2List(dataBean!!.wineryCommentImg))
                binding.etDesc.setText(it.wineryCommentDesc.checkValue())
            }
        }
    }

    private fun initView() {
        initPhotoView()
        EditInputUtils.numEditText(binding.etDesc, binding.tvWordNum, 100)
    }

    private fun initPhotoView() {
        mImageVideoAdapter = UploadImageVideoAdapter(this, 1, imgPathUrlList as ArrayList<String>?)
        //1：78x78的item大小
        mImageVideoAdapter.setDynamictype(1)
        binding.rvImagevideo.addItemDecoration(SpacesRightDec(dip2px(8)))
        binding.rvImagevideo.addItemDecoration(SpacesVerticalDec(dip2px(10)))
        binding.rvImagevideo.adapter = mImageVideoAdapter
        mTouchHelper = RecyUtils.itemTouchHelper(mImageVideoAdapter, imgPathUrlList as ArrayList<String>, Constants.PUBLISH_IMG_MAX)
        viewModel.setItemHelper(binding.rvImagevideo, mTouchHelper, mImageVideoAdapter)
        mImageVideoAdapter.setOnClickListener(this)
    }

    override fun onItemClick(pos: Int, list: ArrayList<String>?) {
        //查看大图
        val desc = binding.etDesc.text.toString()
        val bundle = Bundle()
        bundle.putStringArrayList(Constants.KEY_URLS, list as ArrayList<String>)
        bundle.putInt(Constants.KEY_INDEX, pos)
        bundle.putStringArrayList(Constants.KEY_COMMENT_CONTENT, arrayListOf(desc))
        bundle.putStringArrayList(Constants.KEY_COMMENT_TITLE, arrayListOf())
        ActivityRouter.startActivity(ActivityRouter.WINE_CELLAR.IMG_VIDEO_DETAIL, bundle)
    }

    override fun onAddItemClick() {
        WineryAboutUtils.uploadImgVideo(this, false, imgPathUrlList.size, 9)
    }

    override fun onDeleteItemClick(pos: Int, list: ArrayList<String>?) {
        PopUtils.showOkCancelDialog(this, "确认删除", object : PopUtils.ICallBack {
            override fun clickOk() {
                if (imgPathUrlList.size > pos) {
                    imgPathUrlList.removeAt(pos)
                    ToastUtils.showShort(applicationContext, "删除成功")
                }
                viewModel.setItemHelper(binding.rvImagevideo, mTouchHelper, mImageVideoAdapter)
                mImageVideoAdapter.setData(imgPathUrlList as ArrayList<String>?)
                mImageVideoAdapter.setDynamictype(1)
                mImageVideoAdapter.notifyDataSetChanged()
            }

            override fun clickCancel() {

            }

        }, false, "确认", "取消")
    }

    override fun onVideoCoversClick() {

    }

    //回显数据
    private fun setImgListData(items: MutableList<String>) {
        imgPathUrlList.addAll(items)
        viewModel.setItemHelper(binding.rvImagevideo, mTouchHelper, mImageVideoAdapter)
        mImageVideoAdapter.setData(imgPathUrlList as ArrayList<String>?)
        mImageVideoAdapter.setDynamictype(1)
        mImageVideoAdapter.notifyDataSetChanged()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_enter -> {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    publishCommit()
                }
            }
        }
    }

    //发布
    private fun publishCommit() {
        val wineryCommentDesc = binding.etDesc.text.toString().trim()
        if (imgPathUrlList.size == 0) {
            "图片不能为空".toast()
            return
        }
        if (TextUtils.isEmpty(wineryCommentDesc)) {
            "评论说明不能为空".toast()
            return
        }
        showLoading()
        if (imgPathUrlList.size == 0) {
            editCommit()
        } else {
            val pathList = mutableListOf<String>()
            val indexList = mutableListOf<Int>()
            imgPathUrlList.forEachIndexed { index, s ->
                if (!s.startsWith("http")) {
                    pathList.add(s)
                    indexList.add(index)
                }
            }
            if (pathList.size == 0) {
                //编辑
                editCommit()
                return
            }
            //上传图片
            UploadMediaUtils.uploadImages(pathList as ArrayList<String>?, object : UploadMediaUtils.UploadImageListener {
                override fun onComplete(questionRespT: MultiImageResp?) {
                    questionRespT?.let {
                        var upsuccUrlList = mutableListOf<String>()

                        if (questionRespT.getData().size > 0) {
                            for (i in 0 until questionRespT.getData().size) {
                                upsuccUrlList.add(questionRespT.getData()[i].ok)
                            }
                            indexList.forEachIndexed { index, pathIndex ->
                                imgPathUrlList[pathIndex] = upsuccUrlList[index]
                            }
                            val desc = binding.etDesc.text.toString()
                            val isEdit = dataBean.checkNotNull()
                            var commentId = 0L
                            dataBean?.let {
                                commentId = it.id
                            }
                            viewModel.reqAddOrEditComment(isEdit, commentId, desc, CommonUtil.list2str(imgPathUrlList), dataBean?.wineryName.checkValue())
                        }
                    }
                }
            })
        }
    }

    private fun editCommit() {
        val desc = binding.etDesc.text.toString()
        val isEdit = dataBean.checkNotNull()
        var commentId = 0L
        dataBean?.let {
            commentId = it.id
        }
        viewModel.reqAddOrEditComment(isEdit, commentId, desc, CommonUtil.join(imgPathUrlList.toTypedArray(), ","), dataBean?.wineryName.checkValue())
    }

    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_select_img_video_path_list) {
            if (messageBus.param1 is List<*>) {//图片
                var list = messageBus.param1 as List<String>
                imgPathUrlList.addAll(list)
                viewModel.setItemHelper(binding.rvImagevideo, mTouchHelper, mImageVideoAdapter)
                mImageVideoAdapter.setData(imgPathUrlList as ArrayList<String>?)
                mImageVideoAdapter.setDynamictype(1)
                mImageVideoAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}